package com.heima.user.service.impl;

import com.heima.common.constant.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.thread.UserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    private CacheService cacheService;

    /**
     * 处理关注
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        log.info("【处理关注】--- begin");
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断用户是否登录
        Integer userId = UserThreadLocalUtil.getUser();
        if(userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        if (dto.getOperation() == 0) {
            log.info("【关注行为】");
            // 将对方写入我的关注中
            cacheService.zAdd(BehaviorConstants.APUSER_FOLLOW_RELATION +userId,String.valueOf(dto.getAuthorId()), System.currentTimeMillis());
            // 将我写入对方的粉丝中
            cacheService.zAdd(BehaviorConstants.APUSER_FANS_RELATION+ dto.getAuthorId(), userId.toString(), System.currentTimeMillis());

        } else {
            // 取消关注
            log.info("【取消关注行为】");
            cacheService.zRemove(BehaviorConstants.APUSER_FOLLOW_RELATION + userId, String.valueOf(dto.getAuthorId()));
            cacheService.zRemove(BehaviorConstants.APUSER_FANS_RELATION + dto.getAuthorId(), userId.toString());
        }
        log.info("【处理关注】--- end");

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
